﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.Profile;
using System.Configuration;

namespace Vit.Web.Helpers
{
    public class MembershipHelper
    {
        public static string GetCurrentUserIdentity()
        {
            string userIdentity = "";
            if (HttpContext.Current.User != null && HttpContext.Current.User.Identity != null)
                userIdentity = HttpContext.Current.User.Identity.Name;
            return userIdentity;
        }

        public static SettingsContext GetUserSettingsContext(string userIdentity)
        {
            SettingsContext sc = new SettingsContext();
            sc.Add("UserName", userIdentity);
            if (HttpContext.Current.Request.IsAuthenticated && userIdentity == HttpContext.Current.User.Identity.Name)
                sc["IsAuthenticated"] = true;
            else
                sc["IsAuthenticated"] = false;
            return sc;
        }

        public static Dictionary<string, object> GetUserProfileProperties(string userIdentity)
        {
            SettingsContext sc = GetUserSettingsContext(userIdentity);
            SettingsPropertyValueCollection propertyValues = ProfileManager.Provider.GetPropertyValues(sc, ProfileBase.Properties);
            Dictionary<string, object> dic = new Dictionary<string, object>();
            foreach (SettingsPropertyValue sp in propertyValues)
                dic.Add(sp.Name, sp.PropertyValue);

            return dic;
        }

        public static void SetUserProfileProperties(string userIdentity, Dictionary<string, object> propertyValues, bool addPropertyIfNotDefined)
        {
            SettingsContext sc = GetUserSettingsContext(userIdentity);
            SettingsPropertyValueCollection properties = ProfileManager.Provider.GetPropertyValues(sc, ProfileBase.Properties);
            foreach (KeyValuePair<string, object> kvp in propertyValues)
            {
                if (properties[kvp.Key] == null)
                {
                    if (addPropertyIfNotDefined)
                    {
                        SettingsProperty sp = new SettingsProperty(kvp.Key);
                        SettingsPropertyValue spv = new SettingsPropertyValue(sp);
                        spv.PropertyValue = kvp.Value;
                        properties.Add(spv);
                    }
                    else
                        continue;
                }
                else
                {
                    properties[kvp.Key].PropertyValue = kvp.Value;
                }
            }
            ProfileManager.Provider.SetPropertyValues(sc, properties);
        }
    }
}
